﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using BawangMemo.BackendModels;

namespace BawangMemo.BawangMemoView.View
{
    /// <summary>
    /// TestView.xaml 的交互逻辑
    /// </summary>
    public partial class TestView : UserControl
    {
        List<WordWrapper> _wordlist = new List<WordWrapper>();
        List<WordWrapper> _recited_words = new List<WordWrapper>();
        List<WordWrapper> _word_to_test = new List<WordWrapper>();
        List<WordWrapper> _wrong_wrapper = new List<WordWrapper>();
        ObservableCollection<TestWordInfo> wordsWrong = new ObservableCollection<TestWordInfo>();

        List<string> _meanings = new List<string>();
        List<string> _verbs = new List<string>();
        List<string> _nouns = new List<string>();
        List<string> _adjs = new List<string>();

        private int _num_to_test = 5;
        private int nextindex = 0;

        //private bool sel = true;

        private int right_answer = 0;
        private int selected_answer = 0;

        private string[] answers = new string[5];

        #region Initalization

        public TestView()
        {
            InitializeComponent();
        }
        private MainWindow _mw;
        private CourseWrapper _cw;
        private Test_SetupDia _tsd;

        public const int TAG_THRESHOLD = 10;

        public TestView(CourseWrapper cw, MainWindow _mainwindow, Test_SetupDia tsd)
            : this()
        {            
            _mw = _mainwindow;
            _cw = cw;
            _tsd = tsd;
            TestView_Init();            
        }

        public void TestView_Init()
        {            

            if (_tsd.winner == true)
            {
                radioButton1.Focus();

                _num_to_test = _tsd._number;

                _wordlist = _cw.WordList;

                if (_tsd._type == 0) // recited words
                {
                    _recited_words = _cw.ListOldWords();    //Word to Test, Actually. 
                }
                else if (_tsd._type == 1) // all
                {
                    _recited_words = _cw.WordList;
                }
                else if (_tsd._type == 2) // lists
                {
                    _recited_words = ListRepository.GetList(this._cw, _tsd.SelectedListId);
                }
                else if (_tsd._type == 3) // tags
                {
                    if (_tsd.SelectedTag != null)
                    {
                        _recited_words = TagRepository.ListWordsOfTag(this._cw, _tsd.SelectedTag);
                        if (_recited_words.Count >= TAG_THRESHOLD)
                        {
                            _wordlist = _recited_words;
                        }
                    }
                }
                else
                {
                    _mw.grid1.Children.Clear();
                    return;
                }

                if (_recited_words.Count < _num_to_test)
                    _recited_words = _cw.WordList;

                if (_num_to_test > _recited_words.Count)
                    _num_to_test = _recited_words.Count;

                GetMeanings();
                _word_to_test = Select_Word();

                nextindex = 0;
                WordCard wordcard = _word_to_test[nextindex].GetWordCard();
                SetWord(wordcard);
                wordsWrong = new ObservableCollection<TestWordInfo>();
                this.button_go.IsEnabled = false;
                this.label2.Content = "第1题  , " + "共" + _num_to_test.ToString() + "题";
            }
            else
            {
                _mw.grid1.Children.Clear();
            }
        }

        #endregion

        #region words selection and update

        private void GetMeanings()
        {
            for (int i = 0; i < _wordlist.Count; i++)
            {
                string cur_str = _wordlist[i].GetWordCard().Meaning;
                if (cur_str.Contains("\n"))
                {
                    int pos = cur_str.IndexOf("\n");
                    cur_str = cur_str.Substring(0, pos);
                }
                //string cur_str = i.ToString();

                _meanings.Add(cur_str);
                if (cur_str.Contains("v.")) _verbs.Add(cur_str);
                if (cur_str.Contains("n.")) _nouns.Add(cur_str);
                if (cur_str.Contains("adj.")) _adjs.Add(cur_str);
            }
        }

        private List<WordWrapper> Select_Word()
        {
            _word_to_test = new List<WordWrapper>();
            Random rd = new Random();
            List<int> contain_things = new List<int>();
            for (int i = 0; i < _num_to_test; i++)
            {
                int num = rd.Next(0, _recited_words.Count);
                while (contain_things.Contains(num))
                {
                    num = rd.Next(0, _recited_words.Count);
                }
                contain_things.Add(num);
                _word_to_test.Add(_recited_words[num]);
            }
            return _word_to_test;
        }

        private void SetWord(WordCard wcd)
        {
            this.label1.Content = wcd.Spell;

            Random rd = new Random();
            int correct = rd.Next(0, 5);
            right_answer = correct;
            answers[correct] = wcd.Meaning;

            List<string> l_now = new List<string>();
            int count = 0;

            if (wcd.Meaning.Contains("adj.")) { count++; l_now = _adjs; }
            if (wcd.Meaning.Contains("n.")) { count++; l_now = _nouns; }
            if (wcd.Meaning.Contains("v.")) { count++; l_now = _verbs; }
            if (count != 1) l_now = _meanings;

            for (int i = 0; i <= 4; i++)
            {
                if (i != correct)
                {
                    int index = rd.Next(0, l_now.Count);
                    while (l_now[index].Equals(answers[correct])/* || already.Contains(index)*/)
                    {
                        index = rd.Next(0, l_now.Count);
                    }
                    answers[i] = l_now[index];
                }
            }

            radioText1.Text = "A.   " + answers[0];
            radioText2.Text = "B.   " + answers[1];
            radioText3.Text = "C.   " + answers[2];
            radioText4.Text = "D.   " + answers[3];
            radioText5.Text = "E.   " + answers[4];
        }

        #endregion

        #region button events and radio events

        /// <summary>
        /// Proceed to nextword
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>             
        private void button_go_Click_1(object sender, RoutedEventArgs e)
        {
            goNext();
        }

        private void Window_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.Key == Key.NumPad1 || e.Key == Key.D1)
            { radioButton1.IsChecked = true; button_go.IsEnabled = true; selected_answer = 0; }
            else if (e.Key == Key.NumPad2 || e.Key == Key.D2)
            { radioButton2.IsChecked = true; button_go.IsEnabled = true; selected_answer = 1; }
            else if (e.Key == Key.NumPad3 || e.Key == Key.D3)
            { radioButton3.IsChecked = true; button_go.IsEnabled = true; selected_answer = 2; }
            else if (e.Key == Key.NumPad4 || e.Key == Key.D4)
            { radioButton4.IsChecked = true; button_go.IsEnabled = true; selected_answer = 3; }
            else if (e.Key == Key.NumPad5 || e.Key == Key.D5)
            { radioButton5.IsChecked = true; button_go.IsEnabled = true; selected_answer = 4; }
            else if (e.Key == Key.Enter)
            {
                if (button_go.IsEnabled)
                    goNext();
            }
        }

        private void goNext()
        {
            if (right_answer == selected_answer)
            {
                _word_to_test[nextindex].ChangeScore(3);
            }
            else
            {
                TestWordInfo twi = new TestWordInfo(wordsWrong.Count, _word_to_test[nextindex].Spell, _word_to_test[nextindex].GetWordCard().Meaning);
                _wrong_wrapper.Add(_word_to_test[nextindex]);
                wordsWrong.Add(twi);

                // wintokk 11-6-9
                _word_to_test[nextindex].ChangeScore(0);
            }

            nextindex++;
            if (nextindex >= _num_to_test)
            {
                MessageBoxResult r = MessageBox.Show(_mw, "共" + _num_to_test + "道题，错误数目为" + wordsWrong.Count + "道,查看错误的单词吗？", "测试结果", MessageBoxButton.YesNo);
                if (r == MessageBoxResult.No)
                {
                    //退出
                    //Application.Current.Shutdown();
                }
                else
                {
                    WrongWordDia wwd = new WrongWordDia(_wrong_wrapper, wordsWrong);
                    wwd.ShowDialog();
                    if (wwd.showtag == 1)
                    {
                        MainWindowManager._mainWindow.grid1.Children.Clear();
                        MainWindowManager._mainWindow.grid1.Children.Add(new BankView(_cw, 0));
                        return;
                    }
                }

                button_go.IsEnabled = false;
                r = MessageBox.Show(_mw, "开始新测试吗", "新测试", MessageBoxButton.YesNo);
                if (r == MessageBoxResult.No)
                {
                    radioButton1.IsEnabled = false;
                    radioButton2.IsEnabled = false;
                    radioButton3.IsEnabled = false;
                    radioButton4.IsEnabled = false;
                    radioButton5.IsEnabled = false;
                    MainWindowManager._mainWindow.grid1.Children.Clear();
                    MainWindowManager._mainWindow.grid1.Children.Add(new BankView(_cw, 0));
                    return;
                }
                else
                {
                    radioButton1.IsChecked = false;
                    radioButton2.IsChecked = false;
                    radioButton3.IsChecked = false;
                    radioButton4.IsChecked = false;
                    radioButton5.IsChecked = false;
                    TestView_Init();
                }
            }
            else
            {
                WordCard wordcard = _word_to_test[nextindex].GetWordCard();
                SetWord(wordcard);
                radioButton1.IsChecked = false;
                radioButton2.IsChecked = false;
                radioButton3.IsChecked = false;
                radioButton4.IsChecked = false;
                radioButton5.IsChecked = false;
                button_go.IsEnabled = false;

                this.label2.Content = "第" + (nextindex + 1).ToString() + "题  , " + "共" + _num_to_test.ToString() + "题";
            }
        }

        private void radioButton1_Checked(object sender, RoutedEventArgs e)
        {
            
            button_go.IsEnabled = true;
            selected_answer = 0;
        }

        private void radioButton2_Checked(object sender, RoutedEventArgs e)
        {
            button_go.IsEnabled = true;
            selected_answer = 1;
        }

        private void radioButton3_Checked(object sender, RoutedEventArgs e)
        {
            button_go.IsEnabled = true;
            selected_answer = 2;
        }

        private void radioButton4_Checked(object sender, RoutedEventArgs e)
        {
            button_go.IsEnabled = true;
            selected_answer = 3;
        }

        private void radioButton5_Checked(object sender, RoutedEventArgs e)
        {
            button_go.IsEnabled = true;
            selected_answer = 4;
        }
        #endregion
    }
}
